/**
 * 游戏主流程
 */
import { addBoxToMap, eliminate, initMap } from './map'
import { render } from './renderer'
import { addTicker } from './ticker'
import { intervalTimer } from './utils'
import { hitBottomBorder, hitBottomBox } from './hit'
import { createBox } from './Box'
export * from './config.js'

export function startGame (map) {
  initMap(map)

  const isDownMove = intervalTimer()
  let activeBox = createBox()

  function handleTicker (n) {
    if (isDownMove(n, 1000)) {
      // 不可以超过屏幕底部
      // 1.获取box的底部的所有点
      // 2.看看是不是超过了游戏的row
      if (hitBottomBorder(activeBox) || hitBottomBox(activeBox, map)) {
        // 为了不让box reset
        // box ->map -> -1
        addBoxToMap(activeBox, map)
        // 消行
        eliminate(map)
        activeBox = createBox()
        return
      }

      activeBox.y++
    }
    render(activeBox, map)
  }

  window.addEventListener('keydown', (e) => {
    switch (e.code) {
      case 'ArrowLeft':
        activeBox.x--
        break
      case 'ArrowRight':
        activeBox.x++
        break
      case 'ArrowDown':
        activeBox.y++
        break
      case 'ArrowUp':
        activeBox.rotate()
        break
      default:break
    }
  })
  addTicker(handleTicker)
}
